from strange_io import SIGNATURE, get_format, _load_bytearray

class StrangeColors:
    def __init__(self, colors:list[tuple[int,int,int]]=[], transperent_index=0):
        self.colors:list[tuple[int,int,int]] = colors
        self.transperent_index:int = transperent_index

    def dump(self) -> tuple[list[tuple[int,int,int]],int]:
        return self.colors, self.transperent_index

    def load(self, colors:tuple[list[tuple[int,int,int]],int]):
        self.colors, self.transperent_index = colors

    def dump_bytes(self) -> bytes:
        return self.encode(self.colors)

    def load_bytes(self, data: bytes):
        self.colors = self.decode(data)

    def dump_file(self, path):
        out_file = bytearray()
        header = bytearray(SIGNATURE + b'colors\n')
        out_file += header
        out_file += self.encode(self.colors, self.transperent_index)
        with open(path, 'wb') as f:
            f.write(out_file)

    def load_file(self, path, ignore_type=False):
        if get_format(path) == b'colors' or ignore_type:
            file = _load_bytearray(path, remove_type=True)
            self.colors, self.transperent_index = self.decode(file)
        else:
            raise TypeError('Attempted to load non-colors document as colors document')

    @staticmethod
    def encode(colors:list[tuple[int,int,int]],transperent_index:int) -> bytes:
        out_file = bytearray([])
        if len(colors) > 255:
            raise ValueError('To many colors to encode')
        for color in colors:
            out_file += bytearray(color)
        out_file += bytearray([transperent_index])
        return out_file

    @staticmethod
    def decode(data:bytes) -> tuple[list[tuple[int,int,int]],int]:
        colors = []
        color = []
        for i in data:
            if len(color) == 3:
                colors.append(tuple(color))
                color.clear()
            color.append(i)
        return colors, data[len(data)-1]

#region list-like
    def append(self, color:tuple[int,int,int]):
        self.colors.append(color)

    def extend(self, colors:tuple[int,int,int]):
        self.colors.extend(colors)

    def pop(self, index=None):
        return self.colors.pop(index)

    def __getitem__(self, index):
        return self.colors[index]

    def __setitem__(self, index, color):
        self.colors[index] = color

    def __len__(self):
        return len(self.colors)

    def __str__(self):
        return str(self.colors)
#endregion
